#!/usr/bin/env bash
set -e
if [ "${PDNS_DEBUG}" = "YES" ]; then
  set -x
fi

bindwait ()
{
	configname=$1
	domcount=1
	loopcount=0
	while [ $loopcount -lt 20 ]; do
		sleep 1
		done=$( ($PDNSCONTROL --config-name=$configname --socket-dir=. --no-config bind-domain-status || true) | grep -c 'parsed into memory' || true )
		if [ $done = $domcount ]
			then
			return
		fi
		let loopcount=loopcount+1
	done 
	if [ $done != $domcount ]; then
		echo "Domain parsing failed" >> failed_tests
	fi
}

port=5502
rm -f pdns*.pid

rm -f soa-edit/bind-dnssec.db

now=$(date +%s)
delta=$((now-1418860790)) # Wed Dec 17 23:59:50 2014 UTC
 
$PDNSUTIL --config-dir=soa-edit create-bind-db soa-edit/bind-dnssec.db
$PDNSUTIL --config-dir soa-edit/ set-meta minimal.com SOA-EDIT INCREMENT-WEEKS
faketime -m -f -$delta $PDNS --config-dir=soa-edit &
bindwait

$SDIG 127.0.0.1 $port minimal.com SOA | LC_ALL=C sort
$SDIG 127.0.0.1 $port minimal.com MX | LC_ALL=C sort
$SDIG 127.0.0.1 $port nx.minimal.com MX | LC_ALL=C sort
sleep 15
echo midnight has passed
$SDIG 127.0.0.1 $port minimal.com SOA | LC_ALL=C sort
$SDIG 127.0.0.1 $port minimal.com MX | LC_ALL=C sort
$SDIG 127.0.0.1 $port nx.minimal.com MX | LC_ALL=C sort

kill $(cat pdns*.pid)
rm pdns*.pid
